<template>
	<HeaderNav active-index="1"></HeaderNav>
	
	<!-- 添加标题 -->
	<div class="page-title">
		<h2>{{ classDate?.name || '班级' }} 学生任务完成情况</h2>
	</div>
	
	<TaskContainer>
	  <div class="task-center-content">
		<!-- 图表展示 -->
		<div class="chart-section">
		  <el-card 
			shadow="hover" 
			v-for="(student, index) in list" 
			:key="student.id" 
			class="student-card"
		  >
			<div :id="'task-chart-' + student.id" class="chart"></div>
			<div class="card-actions">
			  <el-button type="warning" size="small" @click="handleApplyTask(index, student)">
				<template #icon>
				  <el-icon><Document /></el-icon>
				</template>
				分配任务
			  </el-button>
			  <el-button type="info" size="small" @click="handlerResetPassword(index, student)">
				<template #icon>
				  <el-icon><Refresh /></el-icon>
				</template>
				重置密码
			  </el-button>
			  <el-button type="danger" size="small" @click="handleDelete(index, student)">
				<template #icon>
				  <el-icon><Lock /></el-icon>
				</template>
				禁用用户
			  </el-button>
			</div>
		  </el-card>
		</div>
	  </div>
	</TaskContainer>
	<!-- 添加底部备案信息 -->
	<Footor></Footor>


	<el-dialog v-model="showDialog" title="分配任务" width="70%" top="10px">
		<GroupTaskListView ref="taskList" v-model="selectedTasks"/>
		<template #footer>
		<div class="dialog-footer">
			<el-button type="primary" @click="handleSave">保存</el-button>
			<el-button @click="showDialog = false">关闭</el-button>
		</div>
		</template>
	</el-dialog>
</template>
	
<script>
import HeaderNav from "@/components/HeaderNav.vue"
import TaskContainer from "@/components/TaskContainer.vue"
import Footor from "@/components/Footor.vue"
import * as echarts from 'echarts'; 
import GroupTaskListView from "../group/GroupTaskListView.vue";
import API from "@/api/index.js"

export default {
	components: {
		HeaderNav,
		TaskContainer, 
		Footor,
		GroupTaskListView, 
	},

  created() {
    this.student_list()
  },

  data() {
		return {
			stu_list : null,
      		classDate: null,
			showDialog: false,
			list: [],
			currentStudent: null, // 添加当前选中的学生
			selectedTasks: [], // 添加选中的任务ID数组
		}
	},
	mounted() {
		this.list.forEach(student => {
			this.initChart(student);
		});
	},
	methods: {
		student_list(){
		API.current_stu_list().then(res => {
			this.classDate = res.clazz;
			this.list = res.student || [];

			// 等待 DOM 更新完成后再初始化图表
			this.$nextTick(() => {
				this.list.forEach(student => {
					// 先检查是否已存在图表实例，如果存在则销毁
					const chartDom = document.getElementById('task-chart-' + student.id);
					const existingChart = echarts.getInstanceByDom(chartDom);
					if (existingChart) {
						existingChart.dispose();
					}
					this.initChart(student);
				});
			});
		}).catch(err => {
			console.error("获取学生列表失败:", err);
		});
		},
		initChart(student) {
			const chartDom = document.getElementById('task-chart-' + student.id);
			const myChart = echarts.init(chartDom);
			const option = {
				title: {
					text: student.name,
					subtext: student.email,
					left: 'center'
				},
				tooltip: {
					trigger: 'item'
				},
				legend: {
					orient: 'vertical',
					left: 'left',
					data: ['未开始', '进行中', '需讲解', '已提交', '已检查', '已完成', '异常题']
				},
				series: [
					{
						name: '任务状态',
						type: 'pie',
						radius: '50%',
						label: {
							position: 'inside',
							formatter: '{c}',
						},
						data: [
							{ value: student['0'], name: '未开始' },
							{ value: student['1'], name: '进行中' },
							{ value: student['2'], name: '需讲解' },
							{ value: student['3'], name: '已提交' },
							{ value: student['4'], name: '已检查' },
							{ value: student['5'], name: '已完成' },
							{ value: student['-1'], name: '异常题' },
						],
						emphasis: {
							itemStyle: {
								shadowBlur: 10,
								shadowOffsetX: 0,
								shadowColor: 'rgba(0, 0, 0, 0.5)'
							}
						}
					}
				]
			};
			myChart.setOption(option);
		},
		handleApplyTask(index, student) {
			this.currentStudent = student; // 保存当前选中的学生
			this.showDialog = true;
		},
		handlerResetPassword(index, student) {
			this.$layer.confirm("您确定要将密码重置为【123456】吗?", $index => {
				API.reset_password_active(student.id, '123456').then(res => {
					this.$layer.msg(res.message);
				}).catch(err => {
					console.error("重置密码请求出错：", err);
				})
				this.$layer.close($index);
			})
		},
		handleDelete(index, student) {
			this.$layer.confirm("您确定要禁用该用户吗?", $index => {
				API.reset_password_active(student.id, '0').then(res => {
					this.$layer.msg(res.message);
				}).catch(err => {
					console.error("禁用用户请求出错：", err);
				})
				this.$layer.close($index);
			})
		},
		handleSave() {
			if (!this.selectedTasks || this.selectedTasks.length === 0) {
        this.$message.warning("请选择至少一个任务");
        return;
      }

      const data = {
        studentId: this.currentStudent.id,
        taskIds: this.selectedTasks // 直接使用双向绑定的数据
      };

      API.assignTasksToStudent(data).then(res => {
        this.$message.success(res.message || '分配任务成功');
        this.showDialog = false;
        this.student_list();
      }).catch(err => {
        console.error("分配任务失败:", err);
        this.$message.error('分配任务失败，请重试');
      });
		}

	}
}
</script>

<style scoped>
.task-center-content {
	display: flex;
	flex-direction: column;
	gap: 20px;
	padding: 0 50px 100px; /* 添加左右两侧的空间 */
	background: linear-gradient(135deg, #151824 0%, #1c1f35 100%);
}

.page-title {
	text-align: left;
	margin: 20px 50px;
	color: #f9f9f9;
}

.chart-section {
	display: flex;
	flex-wrap: wrap;
	gap: 20px;
}

.student-card {
	flex: 0 1 calc(20% - 20px); /* 每行展示5个学生，减去间距 */
	box-sizing: border-box;
}

.chart {
	width: 100%;
	height: 200px; /* 调整图表高度以适应布局 */
}

.card-actions {
	display: flex;
	justify-content: space-around;
	margin-top: 10px;
}

</style>



